import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../shared/smartadmin.config';
import { Router,ActivatedRoute} from "@angular/router"; //路由引入
declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-order-ft',
	templateUrl: './order-ft.component.html',
	styleUrls:['./order-ft.component.css']
})
export class OrderFtComponent implements OnInit {
	orderCode = ''
	isPush = ''
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	companyId:string = '';
	deviceId:string = '';//设备ID
	startTime_table:string = '';
	endTime_table:string = '';
	carNumber:string = ''; //车牌号码
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	activeSelected:string='';
	exType:string = '';
	dType:string = '1';
	allChecked: boolean = false; // 全选状态
	selected: any[] = []; // 选中的数据
	selectedRow:any;
	startTime_chart:string='';
	endTime_chart:string='';
	isChartView=false;
	//画轨迹的数据
	drawTrackArr:any;
	isMapView=false;
	specifyId={
		picker1:'datetimepicker3',
		picker2:'datetimepicker4'
	}
	specifyTime={
		startTime:'',
		endTime:'',
	}
	InputTime:any = {
		startTime:'',
		endTime:''
	};//父级传子组件的时间
	inputCompanyTreeCarData:any = {};//车辆运行状态模块跳转该页面传递过来的参数
	constructor(private jsonApiService: JsonApiService,private router: Router,private activatedRoute: ActivatedRoute,) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.inputCompanyTreeCarData = JSON.parse(common.getCookie('jumpExceptionOrderList'));
		});
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime_table=time.startTime;
		this.endTime_table=time.endTime;
	} 
	getSelectChartTime(time){
		this.startTime_chart=time.startTime;
		this.endTime_chart=time.endTime;
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	ngOnInit() {
		// if(common.getCookie('jumpExceptionOrderList')){
		// 	this.orderStatus = this.inputCompanyTreeCarData.type;
		// 	this.searchKey = this.inputCompanyTreeCarData.deviceId;
		// 	this.startTime_table = this.InputTime.startTime = this.inputCompanyTreeCarData.startTime;
		// 	this.endTime_table = this.InputTime.endTime = this.inputCompanyTreeCarData.endTime;
		// 	this.load();
		// 	common.clearCookie('jumpExceptionOrderList');
		// }else{
		// 	this.load()
		// }
		let dateRange = common.getRecentDaysDateTime(7);
		this.startTime_table = this.InputTime.startTime = dateRange.startTime;
		this.endTime_table = this.InputTime.endTime = dateRange.endTime;
		this.load()
	}
	runParent(value){
		this.drawTrackArr=value;
	}
	showMapView(val){
		this.isMapView = val;
	}
	//订单查看
	drawAbnormalChart(){
		if(!this.selectedRow){
			this.jsonApiService.message('先选择需要查看折线图的车辆');
			return;
		}
		if(!this.startTime_chart||!this.endTime_chart){
			this.jsonApiService.message('异常起始时间不能为空');
			return;
		}
		let timeCheck=common.correctTimeParams(this.startTime_chart,this.endTime_chart,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let params={
			deviceId:this.selectedRow.deviceId,
			startTime:this.startTime_chart,
			endTime:this.endTime_chart,
			coefficient:this.selectedRow.coefficient,
		}
		this.selectedRow=params;
		
	}
	checkAbnormal(row){
		this.activeSelected = row.id;
		this.startTime_chart = row.emptyLoadDate;
		let temUnloadEndDate:any,emptyLoadToS:any;
		if(!row.unloadEndDate){
			emptyLoadToS = common.mmsstoTimestamp(row.emptyLoadDate);
			temUnloadEndDate = common.getTimeMmss(new Date(emptyLoadToS+1*24*60*60*1000));
		}
		var unloadEndDate = row.unloadEndDate?row.unloadEndDate:temUnloadEndDate;
		this.endTime_chart = unloadEndDate;
		this.isChartView = true;
		row.startTime = row.emptyLoadDate;
		row.endTime = unloadEndDate;
		this.specifyTime = {
			startTime:this.startTime_chart, 
			endTime:this.endTime_chart,
		}
		this.lineParamDeal(row);
	}
	//获取传感器通道参数
	lineParamDeal(row){
		let reqdata = 'deviceId=' + row.deviceId;
		this.jsonApiService.http("realtime/getRealTimeData.html", reqdata).subscribe(result => {
			if(result.success&&result.data){
				row.coefficient = result.data.coef;
				this.selectedRow = row;
			}
		})
	}
	// 跳转订单监控
	jumpOrderManagenment(row) {
		let queryParams = {
			orderCode: row.taskId,
			startTime: row.emptyLoadDate,
			endTime: row.uploadTime,
		}
		let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
		common.setCookie('jumpFromTransportMOrderAlert', JSON.stringify(queryParams));
		window.open(BaseURL + '#/data-statistics/task/order-management');
	}
	//处理 跳转到数据优化页面
	jumpOptimization(row){
		var junmpData={
				deviceId:row.deviceId,
				carNumber:row.carNumber,
				startDate:row.emptyLoadDate,
				endDate:row.unloadEndDate
			}
		console.log(row,junmpData)
		this.router.navigate(['/system-config/data-optimization'],{ queryParams:junmpData});
		setTimeout(function(){
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display','none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display','block');
		},300)
	}
	/**
	 * 手动执行算法模块===============================================================================================
	 */
	zeroBeforeDate:string = '';  //手动执行算法开始时间
    zeroAfterDate:string = '';  //手动执行算法结束时间
	runMatlabDeviceId:string = '';  //手动执行算法设备ID
   //初始化时间[手动执行算法]
    initDate() {
			let that=this;
			return new Promise(function(resolve,error){
					System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
							System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
									$("#datePicker1").datetimepicker({ //时间插件
											format: "yyyy-mm-dd hh:ii:ss",
											language: "zh-CN",
											autoclose: true,
									}).on("changeDate", function(e) {
											var date = e.date;
											var time = common.getTimeMmss(date);
											that.zeroBeforeDate = time;
											$("#datePicker2").datetimepicker("setStartDate", time);
									});
									$("#datePicker2").datetimepicker({ //时间插件
											format: "yyyy-mm-dd hh:ii:ss",
											language: "zh-CN",
											autoclose: true,
									}).on("changeDate", function(e) {
											var date = e.date;
											var time = common.getTimeMmss(date);
											that.zeroAfterDate = time;
											$("#datePicker1").datetimepicker("setEndDate", time);
									});
									resolve();
							})
					})
			})
    }
   //手动执行算法
    runMatlab(row,modal) {
        this.initDate().then(()=>{
            this.zeroBeforeDate = '';
            this.zeroAfterDate = '';
            this.zeroBeforeDate = row.emptyLoadDate;
            $("#datePicker2").datetimepicker("setStartDate", this.zeroBeforeDate);
        });
        this.runMatlabDeviceId = row.deviceId;
        modal.show();
    }
    runMatlabCancel(modal){
        modal.hide();
    }
    // 手动执行算法
    runMatlabConfirm(modal) {
        if (this.zeroBeforeDate && this.zeroAfterDate) {
            if (common.mmsstoTimestamp(this.zeroBeforeDate) - common.mmsstoTimestamp(this.zeroAfterDate) > 0) {
                this.jsonApiService.message('上货前置零时间不能大于卸货后置零时间');
                return;
            }
            if (new Date().getTime() - common.mmsstoTimestamp(this.zeroAfterDate) < 0) {
                this.jsonApiService.message('卸货后置零时间不能大于当前时间');
                return;
            }
            let timeCheck = common.correctTimeParams(this.zeroBeforeDate, this.zeroAfterDate, 0)
            if (!timeCheck.status) {
                this.jsonApiService.message(timeCheck.message);
                return;
            }
        } else {
            this.jsonApiService.message('上货前置零时间,卸货后置零时间不能为空');
            return;
        }
        let reqdata: any = {
            deviceId: this.runMatlabDeviceId,
            startTime: this.zeroBeforeDate,
            endTime: this.zeroAfterDate,
//          fullLoadTime: this.upEndDate,
        }
        this.jsonApiService.confirm_message('您确定要执行算法？').then(() => {
            this.jsonApiService.http_obj("orderController/fixWeightByHand.html", reqdata).subscribe(data => {
                this.jsonApiService.message(data.message);
                if (data.success) {
                    modal.hide();
                    if(this.isChartView){
                        this.startTime_chart = this.zeroBeforeDate;
                        this.endTime_chart = this.zeroAfterDate;
                        this.specifyTime = {
                            startTime:this.startTime_chart, 
                            endTime:this.endTime_chart,
                        }
                        this.drawAbnormalChart();
                    }
                }
            })
        });
    }
	//删除
	delete_row(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("exceptionOrderForHaiLuo/deleteExceptionOrderById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	//  初始化加载list数据
	load() {
		let timeCheck=common.correctTimeParams(this.startTime_table,this.endTime_table,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		
		this.allChecked = false; // 全选置空
		this.selected = []
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				exType: this.exType == '' ? null : this.exType,
				deviceId: this.deviceId,
				companyId: this.selectedCompanyId,
				dType: this.dType,
				carNumber:this.carNumber,
				startTime:this.startTime_table,
				endTime:this.endTime_table,
				orderCode: this.orderCode,
				isPush: this.isPush
				// searchKey:this.searchKey
			}
		}
		this.jsonApiService.json_http("errorOrder/findOrderList.html", data).subscribe(result => {
			if(!result.isSuccess){
				this.jsonApiService.message(result.message);
				return;
			}
			this.tableData = result.exhibitDatas;
			this.totalCount = result.recordCount;
		})
	}
	ngOnDestroy(){
		document.onclick = null;
	}
	//刷新
	refresh(){
		this.load();
	}
	//查询
	table_search(){
		this.curPage=1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	// 关闭图标
	closeChart():void{
		this.isChartView = false;
	}
	// 批量推送
	pushAll(){
		if(this.selected.length){
			this.jsonApiService.json_http("errorOrder/pushRErrorOrderToFanTu.html", this.selected).subscribe(result => {
				this.load();
				this.jsonApiService.message(result.message);
				this.jsonApiService.message(`成功${result.data.successCount}条失败${result.data.failCount}条`);
			});
		}else {
			this.jsonApiService.message('请勾选订单推送');
		}
	}
	//单独推送
	pushItem(row){
		let selected = this.selected.length ? this.selected : [row.orderCode]
		this.jsonApiService.json_http("errorOrder/pushRErrorOrderToFanTu.html", selected).subscribe(result => {
			this.load();
			this.jsonApiService.message(result.message);
		});
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId
	rowSelected(row,e,index){
		var index = $.inArray(row.orderCode, this.selected);
		if(index === -1) {
			row.isChecked = true;
			this.selected.push(row.orderCode);
		}else{
			row.isChecked = false;
			this.selected.splice(index, 1);
		}
		this.selected.length === this.pageSize?this.allChecked = true:this.allChecked = false; //判断是否全选状态
	}
	//table 全部选中
	allSelected(){
		this.allChecked = !this.allChecked;
		if(!this.allChecked){
			for(let item of this.tableData){
				item['isChecked'] = false;
			}
			this.selected = [];
		}else{
			for(let item of this.tableData){
				item['isChecked'] = true;
				this.selected.push(item.orderCode);
			}
		}
	}
}
